package model;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Description：针对博客实现的功能
 * 1.新增blog（编辑页）
 * 2.查询blog list（列表页）
 * 3.查询指定blog（详情页）
 * 4.删除指定博客（详情页）
 * User：chenshu
 * Date：2023-12-07
 * Time：00:30
 */
public class BlogDao {
    public void insert(Blog blog) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            //1.建立连接
            connection = DBUtil.getConnection();
            //2.构造SQL语句
            String sql = "insert into blog values(null, ?, ?, ?, now())";
            statement = connection.prepareStatement(sql);
            statement.setString(1, blog.getTitle());
            statement.setString(2, blog.getContent());
            statement.setInt(3, blog.getUserId());
            //3.执行sql
            int ret = statement.executeUpdate();
            if (ret == 1) {
                System.out.println("插入成功！");
            } else {
                System.out.println("插入失败！");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection, statement, null);
        }
    }

    public List<Blog> selectAll() {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Blog> blogs = new ArrayList<>();
        try {
            //1.connect
            connection = DBUtil.getConnection();
            //2.construct sql
            String sql = "select * from blog order by postTime desc";
            statement = connection.prepareStatement(sql);
            //3.execute sql
            resultSet = statement.executeQuery();
            //4.traversal result
            while (resultSet.next()) {
                Blog blog = new Blog();
                blog.setBlogId(resultSet.getInt("blogId"));
                blog.setTitle(resultSet.getString("title"));
                //博客列表页，只需要正文的摘要就可以
                String content = resultSet.getString("content");
                if (content.length() > 100) {
                    blog.setContent(content.substring(0, 100));
                } else {
                    blog.setContent(content);
                }
                blog.setUserId(resultSet.getInt("userId"));
                blog.setPostTime(resultSet.getTimestamp("postTime"));
                blogs.add(blog);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection, statement, resultSet);
        }
        return blogs;
    }
    public Blog selectOne(int blogId) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtil.getConnection();

            String sql = "select * from blog where blogId = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, blogId);

            resultSet = statement.executeQuery();

            if (resultSet.next()) {
                Blog blog = new Blog();
                blog.setBlogId(resultSet.getInt("blogId"));
                blog.setTitle(resultSet.getString("title"));
                blog.setContent(resultSet.getString("content"));
                blog.setUserId(resultSet.getInt("userId"));
                blog.setPostTime(resultSet.getTimestamp("postTime"));
                return blog;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return null;
    }
    public void delete(int blogId) {
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = DBUtil.getConnection();
            String sql = "delete from blog where blogId = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,blogId);
            int ret = statement.executeUpdate();
            if (ret == 1){
                String log = "insert into log values(null, -1, '删除博客成功', now())";
                Statement s = connection.createStatement();
                s.executeUpdate(log);
            } else {
                System.out.println("删除失败！");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection,statement,null);
        }
    }

    public void deleteByUserId(int userId) {
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = DBUtil.getConnection();
            String sql = "delete from blog where userId = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,userId);
            int ret = statement.executeUpdate();
            if (ret == 1){
                System.out.println("删除成功！");
            } else {
                System.out.println("删除失败！");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection,statement,null);
        }
    }

    public List<Blog> selectByUserId(int userId) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Blog> blogs = new ArrayList<>();
        try {
            //1.connect
            connection = DBUtil.getConnection();
            //2.construct sql
            String sql = "select * from blog where UserId = ? order by postTime desc";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,userId);
            //3.execute sql
            resultSet = statement.executeQuery();
            //4.traversal result
            while (resultSet.next()) {
                Blog blog = new Blog();
                blog.setBlogId(resultSet.getInt("blogId"));
                blog.setTitle(resultSet.getString("title"));
                //博客列表页，只需要正文的摘要就可以
                String content = resultSet.getString("content");
                if (content.length() > 50) {
                    blog.setContent(content.substring(0,50));
                    System.out.println(blog.getContent());
                } else {
                    blog.setContent(content);
                }
                blog.setUserId(resultSet.getInt("userId"));
                blog.setPostTime(resultSet.getTimestamp("postTime"));
                blogs.add(blog);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection, statement, resultSet);
        }
        return blogs;
    }
}
